// import 'package:flutter_baidu_map/flutter_baidu_map.dart';
import 'dart:io';

import 'package:qgchat/common/global/global.dart';
import 'package:bloc/bloc.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qgchat/http/apis/common.dart';
import 'package:qgchat/http/models/newanchorModel.dart';

enum SameCityEvent { refresh, load }

class SameCityBloc extends Bloc<SameCityEvent, List<NewanchorModel>> {
  @override
  List<NewanchorModel> get initialState => [];

  @override
  Stream<List<NewanchorModel>> mapEventToState(SameCityEvent event) async* {
    bool inv = await location();
    if (!inv) return;
    switch (event) {
      // 刷新同城列表
      case SameCityEvent.refresh:
        List<NewanchorModel> list = await _refresh();
        yield list.map((i) => i).toList();
        break;
      // 加载同城列表
      case SameCityEvent.load:
        List<NewanchorModel> list = await _load();
        yield list.map((i) => i).toList();
        break;
    }
  }

  String _loc; // 定位
  int _page = 1; // 分页
  List<NewanchorModel> _list = []; // 同城列表

  /// 刷新同城列表
  Future<List<NewanchorModel>> _refresh() async {
    _page = 1;
    _list = await _getlist();
    return _list;
  }

  /// 加载同城列表
  Future<List<NewanchorModel>> _load() async {
    _page = ++_page;
    List<NewanchorModel> list = await _getlist();
    _list.addAll(list);
    return _list;
  }

  /// 获取同城列表
  Future<List<NewanchorModel>> _getlist() async {
    if (_loc == null) return const <NewanchorModel>[];
    return await CommonApis.samecityanchor(
      "$_loc",
      page: _page,
    );
  }

  /// 权限判断 高德定位
  location() async {
    Future<bool> requestPermission() async {
      final permissions = await PermissionHandler()
          .requestPermissions([PermissionGroup.location]);
      if (permissions[PermissionGroup.location] == PermissionStatus.granted) {
        return true;
      } else {
        showToast("必须拥有定位权限才可以查看同城主播");
        return false;
      }
    }

    if (await requestPermission()) {
      // final location = await AmapLocation.instance.fetchLocation();
      // log(location.province);
      // final province = location.province; //街道名称
      // _loc = province;
      // if (_loc == null) {
      //   showToast("定位失败");
        return false;
      // }
      // return true;
    }
  }
}
